const router = require("koa-router")();
const DB = require("../../module/db");
const tools = require("../../module/tools");
// const bodyParser = require('koa-bodyparser');

router.get("/", async (ctx) => {
  let res = await DB.find("articlecate", {});
  let articalcateList = tools.getArticleData(res);
  await ctx.render("admin/articalcate/list.html", {
    articalcateList,
  });
});
router.get("/addArticalcate", async (ctx) => {
  let res = await DB.find("articlecate", { pid: "0" });
  await ctx.render("admin/articalcate/add.html", {
    firstCateList: res,
  });
});
router.post("/doAddArticalcate", async (ctx) => {
  let addDate = ctx.request.body;
  let status = parseInt(addDate.status);
  addDate.status = status;
  addDate.add_time = new Date();
  let res = await DB.insert("articlecate", addDate);
  console.log("添加数据成功", res);
  ctx.redirect(ctx.state.__HOST__ + "/admin/articalcate");
});
router.get("/edit", async (ctx) => {
  let cateId = ctx.request.query._id;
  let res = await DB.find("articlecate", { _id: DB.getObjectId(cateId) });
  await ctx.render("admin/articalcate/edit.html", {
    obj: res[0],
  });
});
router.post("/doEdit", async (ctx) => {
  let { _id, title, description, keywords, status } = ctx.request.body;
  await DB.update(
    "articlecate",
    { _id: DB.getObjectId(_id) },
    {
      title: title,
      description: description,
      keywords: keywords,
      status: status,
    }
  );
  ctx.redirect(ctx.state.__HOST__ + "/admin/articalcate");
});
// router.get("/delate", async (ctx) => {
//   let delateId = ctx.request.query._id;
//   let result = await DB.delate("articlecate", {
//     _id: DB.getObjectId(delateId),
//   });
//   if (result.n !== 0) {
//     console.log("删除成功");
//   }
//   ctx.redirect(ctx.state.__HOST__ + "/admin/articalcate");
// });
module.exports = router.routes();
